<?php
class Cabin extends Page {

	static $db = array(
		'Recipient' => 'Varchar(255)',
		'ConfirmationText' => 'HTMLText',
	    'AvailablePlace' => 'Int'
	);
	
	static $has_many = array(
		'Bookings' => 'CabinBooking',
		'BookedDates' => 'CabinBookedDates'
	);
	
	
	function getCMSFields() {
		$fields = parent::getCMSFields();
		
		$fields->addFieldToTab('Root.Content.Einstellungen', new TextField('Recipient','Reservationsempfänger'));
        $fields->addFieldToTab('Root.Content.Einstellungen', new NumericField('AvailablePlace','Anzahl Plätze'));
		$fields->addFieldToTab('Root.Content.Einstellungen', new HtmlEditorField('ConfirmationText','Bestätigungstext'));
				
		$reservationTable = new DataObjectManager(
			$this,
         	'Bookings',
         	'CabinBooking',
			array('Name' => 'Name','DateFromNice' => 'von','DateToNice' => 'bis'),
			'getCMSFields_forPopup',
			"CabinID = {$this->ID} AND (DateTo >= CURDATE() OR DateFrom >= CURDATE())",
			'DateFrom ASC'
      		);
		$reservationTable->popupClass = 'CabineBookingObjectManager_Popup'; 
		$fields->addFieldToTab('Root.Content.Reservationen',$reservationTable);

		$bookedOutTable = new DataObjectManager(
			$this,
         	'BookedDates',
         	'CabinBookedDates',
			array('DateFromNice' => 'von','DateToNice' => 'bis','OccupiedPlaces'=>"Belegung"),
			'getCMSFields_forPopup',
			"CabinID = {$this->ID} AND (DateTo >= CURDATE() OR DateFrom >= CURDATE())",
			'DateFrom ASC'
      		);
		//$availableTable->popupClass = 'CabineBookingObjectManager_Popup'; 
		$fields->addFieldToTab('Root.Content.Verfügbarkeit',$bookedOutTable);
		
		return $fields;
	}
	
	public function checkIfAvailable($dateFrom, $dateTo) {

		$bookings = DataObject::get('CabinBookedDates',
			'CabinID = ' .$this->ID . " AND ( 
			'".$dateFrom."' BETWEEN `CabinBookedDates`.dateFrom AND DATE_SUB(`CabinBookedDates`.dateTo,INTERVAL 1 DAY)
			OR
			'".$dateTo."' BETWEEN DATE_ADD(`CabinBookedDates`.dateFrom,INTERVAL 1 DAY) AND `CabinBookedDates`.dateTo
			OR 
			('".$dateFrom."' < `CabinBookedDates`.dateFrom AND ".$dateTo." > `CabinBookedDates`.dateTo)
			)");
		
		

		if ($bookings) {
			return false;
		}
		return true;	
	}
	
}
 
class Cabin_Controller extends Page_Controller {
	function init(){
		parent::init();
	}
	

	
	function BookingForm() {
		$fieldset = CabinBooking::getFormFields();
		$fieldset->push(new HiddenField('CabinID','CabinID',$this->ID));
		$actions = new FieldSet(
			new FormAction('doBooking', 'Absenden')
		);
		
		$validation = new CabinBookingFields(array('NumberOfPersons','Name','FirstName','Street','Zip','City','Country','TelNumber','email'));

		return new Form($this, 'BookingForm', $fieldset, $actions, $validation);
	}
	
	
	/**
	 * @param array $data
	 * @param Form $form
	 * @return void
	 */
	function doBooking($data,$form) {

		if ($form->validate()) {
			$booking = new CabinBooking();
			$form->saveInto($booking);
			$booking->CabinID = $this->ID;
			$booking->write();
			
			$email = new Email();
			$email->setTemplate('BookMail');
			$email->setTo($this->Recipient);
	        $email->setFrom( $booking->Email );
	        $email->setSubject( 'Neue Reservation' );
	        $data['Title'] = $this->Title;
	        $email->populateTemplate($data);
			$email->send();
			Director::redirect($this->URLSegment . '/confirmation');
		} else {
			Session::set("FormInfo.Form_BookingForm.data", $data);
			return Director::redirectBack();
		}
	}
	
	public function BookingOverview() {
		Requirements::css("fieldExtension/css/ui.datepicker.css");
		Requirements::css("cabinBooker/css/style.css");
		Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
		Requirements::javascript(THIRDPARTY_DIR . '/jquery/plugins/livequery/jquery.livequery.js');
        Requirements::javascript(THIRDPARTY_DIR . '/jquery-ui/jquery.ui.core.js');
        Requirements::javascript(THIRDPARTY_DIR . '/jquery-ui/jquery.ui.datepicker.js');
	    
	    $bookedDates = DataObject::get('CabinBookedDates',
			"CabinID = {$this->ID} AND (DateTo >= '".date('Y-m-01')."' OR DateFrom >= ".date('Y-m-01').")",'DateFrom');
	    
	    $jsDateScript = "var bookedDates = new Array(\n";
		if ($bookedDates) {
		    
			foreach ($bookedDates AS $bookedDate) {
				$jsDateScript .= "new Array(new Date('".date('r',strtotime($bookedDate->DateFrom))."'),";
				$jsDateScript .= ($bookedDate->DateTo)?"new Date('".date('r',strtotime($bookedDate->DateTo))."'),":"null,";
				$jsDateScript .= $this->AvailablePlace . ",";
				$jsDateScript .= $bookedDate->OccupiedPlaces;
				$jsDateScript .= "),";
		    	//$jsArray[] = array(date('Y,m,d',strtotime($bookedDate->DateFrom)),date('Y,m,d',strtotime($bookedDate->DateTo)));
		    }
		    $jsDateScript = substr($jsDateScript,0,strlen($jsDateScript)-1);   
		}
		$jsDateScript .= "\n);\n";
		$jsDateScript .= "var availablePlaces = " . $this->AvailablePlace . ";\n";
	    
	    $datePickerController = new CalendarPickerField_Controller();
	    $calLang = $datePickerController->CalendarLang();
	    $calLang = substr($calLang,1,strlen($calLang)-2);

	    Requirements::customScript($jsDateScript);
	    Requirements::customScript('
function daysInMonth(month,year) {
var m = [31,28,31,30,31,30,31,31,30,31,30,31];
if (month != 2) return m[month - 1];
if (year%4 != 0) return m[1];
if (year%100 == 0 && year%400 != 0) return m[1];
return m[1] + 1;
}	    
jQuery(document).ready(function(){
    var prevDayOcc = 0;
	jQuery("#OverviewCalendar").datepicker(
			{
				minDate: new Date('.date('Y,').(intval(date('m'))-1).date(',d').'),
				onSelect: function(dateText, inst) {
				   var infoBox = $("#InfoBox");
				   var date = $(this).datepicker("getDate");
	               var freePlaces = availablePlaces;
	               var occupiedPlaces = 0;
	               var found = false;
                   for(var i=0; i < bookedDates.length; i++ ) {
                       if (bookedDates[i][0].getTime() <= date.getTime() && bookedDates[i][1].getTime() > date.getTime()) {
                          occupiedPlaces += bookedDates[i][3];
                       }
                   }   
	               if (freePlaces - occupiedPlaces < 1) {
                       freePlaces = 0;  
                   } else {
                       freePlaces = freePlaces-occupiedPlaces;
                   }    
	               
	               infoBox.find(".info-date").text("Belegung " + dateText + ":");
	               infoBox.find(".info-booked").text("Belegt: " + occupiedPlaces);
	               infoBox.find(".info-free").text("Frei: " + freePlaces);
	               infoBox.show();
	               return false;
	            },

	            onChangeMonthYear: function(year, month, inst) {
	               var day = daysInMonth(month-1,year);
	               var lastDay = new Date(year,month-2,day);
	               prevDayOcc = 0;
	               
                    for(var i=0; i < bookedDates.length; i++ ) {
                       if (bookedDates[i][0].getTime() <= lastDay.getTime() && bookedDates[i][1].getTime() > lastDay.getTime()) {
                          prevDayOcc += bookedDates[i][3];
                       }
                    } 
	            },
				beforeShowDay: function(date) {
					var dayConfig = new Array();
					var freePlaces = availablePlaces;
					var cssClass= "opFix free";
					var dateTo = false;
					var bookedOut = false;
					dayConfig.push(true);
					var occupiedPlaces = 0;
					
					for(var i=0; i < bookedDates.length; i++ ) {
                       if (bookedDates[i][0].getTime() <= date.getTime() && bookedDates[i][1].getTime() > date.getTime()) {
                          occupiedPlaces += bookedDates[i][3];
                       }
	                   if (freePlaces - occupiedPlaces < 1) {
	                       if (freePlaces - prevDayOcc > 0) {
	                           cssClass = "bookedEvening";  
	                       } else {
	                           cssClass = "booked";  
	                       }
	                   } else {
	                       if (freePlaces - prevDayOcc < 1) {
	                           cssClass = "bookedMorning";
	                       }
	                   }  
	                   
					}
					prevDayOcc = occupiedPlaces;
					dayConfig.push(cssClass);
					return dayConfig;
					
				},'.$calLang.'
			
			}
			
			
	);
});	
	    
	    ');
	    
		return '
				<table class="legendTable">
					<tr>
						<td class="freelegend legend"></td>
						<td class="legend"></td>
						<td>freie Plätze</td>
					</tr>
					<tr>
						<td class="bookedlegend legend"></td>
						<td></td>
						<td>ausgebucht</td>
					</tr>
					<tr>
						<td class="bookedEveninglegend legend"></td>
						<td class="bookedMorninglegend legend"></td>
						<td>Nacht ausgebucht</td>
					</tr>

				</table>
		';
	}

	
}

?>